# -*- coding:utf-8 -*-
"""
Python 3.7
Author：刘爽、何若溥
Time：2022/08/25
"""

import os
import paramiko
from common.fileUtil import getProperties
from common.path import CONFIGPATH, PICPATH
from ftplib import FTP



class FtpUtil:
    def __init__(self, ftp_host, ftp_port, ftp_user, ftp_passwd):
        try:
            transport = paramiko.Transport((ftp_host, ftp_port))
            transport.connect(username=ftp_user, password=ftp_passwd)
            self.sftp = paramiko.SFTPClient.from_transport(transport)
        except Exception as e:
            print("ftp连接失败，报错如下：\n", e)

    def upload(self, local_path, remote_path):
        try:
            self.sftp.put(local_path, remote_path)
        except Exception as e:
            print("ftp图片上传失败，报错如下：\n", e)

    def close(self):
        if self.sftp is not None:
            self.sftp.close()
            self.sftp = None

    def remove_directory(self, directory):
        file_list = self.sftp.listdir(directory)

        for file_name in file_list:
            try:
                self.sftp.remove(f'{directory}/{file_name}')
                print(f"Deleted file: {file_name}")
            except:
                # 如果删除文件失败，则尝试删除目录（递归调用）
                self.remove_directory(f'{directory}/{file_name}')

        try:
            self.sftp.rmdir(directory)
            print(f"Deleted directory: {directory}")
        except Exception as e:
            print(f"Failed to delete directory: {directory}")
            print(e)
        print("所有文件清理成功")
        try:
            self.sftp.mkdir(directory)
            print(f"Created directory: {directory}")
        except Exception as e:
            print(f"Failed to create directory: {directory}")
            print(e)

        print("文件夹重新创建成功")


if __name__ == '__main__':
    db_config = getProperties(CONFIGPATH)
    # 获取指定目录下的所有文件
    file_list = os.listdir(PICPATH)

    # 定义一个变量来存储找到的图片文件名
    file_name = None

    # 初始化文件名列表
    file_names = []

    # 遍历文件列表，找到所有符合条件的图片文件
    for file in file_list:
        if file.endswith(".png"):  # 只处理后缀名为.png的文件
            if "Bug状态统计图" in file or "今日Bug情况统计图" in file or "未解决Bug严重等级统计图" in file or "未解决Bug指派人统计图" in file:
                file_names.append(file)

    # 检查是否找到了符合条件的图片文件
    if not file_names:
        # 如果没有找到符合条件的图片文件，可以根据需要进行适当的处理
        print("未找到符合条件的图片文件")
        exit()  # 终止程序

    # 连接FTP服务器并上传图片
    ftp_conn = FtpUtil(db_config["ftp_host"], int(db_config["ftp_port"]), db_config["ftp_user"],
                       db_config["ftp_passwd"])

    # 清理文件夹
    directory = "/root/bug_statistic"
    directory2 = "/bug_statistc"
    ftp_conn.remove_directory(directory)
    ftp_conn.remove_directory(directory2)

    # 上传图片
    for file_name in file_names:
        try:
            ftp_conn.upload(os.path.join(PICPATH, file_name), f"/root/bug_statistic/{file_name}")
            pic_url = f'139.196.253.94:80/bug_statistic/{file_name}'
            print(pic_url)
        except Exception as e:
            print(f"文件上传失败: {str(e)}")